import { Table, Card } from 'antd'
import { useState, useEffect } from 'react'
import styled from 'styled-components'

const TableContainer = styled(Card)`
  .ant-card-body {
    padding: 0;
  }
`

export default function ProTable({
    columns,
    request,
    toolbar,
    searchForm,
    pagination = true,
    ...props
}) {
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState([])
    const [pageInfo, setPageInfo] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    })

    const fetchData = async (params = {}) => {
        if (!request) return

        setLoading(true)
        try {
            const { data: responseData, total } = await request({
                ...params,
                current: pageInfo.current,
                pageSize: pageInfo.pageSize,
            })
            setData(responseData)
            setPageInfo(prev => ({ ...prev, total }))
        } catch (error) {
            console.error('获取数据失败:', error)
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        fetchData()
    }, [pageInfo.current, pageInfo.pageSize])

    const handleTableChange = (pagination, filters, sorter) => {
        setPageInfo(prev => ({
            ...prev,
            current: pagination.current,
            pageSize: pagination.pageSize,
        }))
    }

    return (
        <TableContainer>
            {searchForm}
            {toolbar}
            <Table
                columns={columns}
                dataSource={data}
                loading={loading}
                pagination={
                    pagination
                        ? {
                            ...pageInfo,
                            showSizeChanger: true,
                            showQuickJumper: true,
                            showTotal: total => `共 ${total} 条`,
                        }
                        : false
                }
                onChange={handleTableChange}
                {...props}
            />
        </TableContainer>
    )
} 